package com.health.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.health.service.SetMealService;
import com.health.utils.QiNiuUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CleanImgJob {

    public static final Logger LOGGER = LogManager.getLogger(CleanImgJob.class);

    @Reference
    private SetMealService setMealService;

    /**
     * 清除七牛云上未被使用的图片
     * 每天凌晨4点运行
     */
    @Scheduled(cron = "0 0 4 * * ? ")
    public void cleanImg() {
        LOGGER.info("【定时任务-清除七牛云多余图片】运行开始>>>>>>start");

        try {
            //查询数据库中的所有图片
            List<String> imgDb = setMealService.findImgs();
            //查询七牛云上的所有图片
            List<String> imgQiNiu = QiNiuUtil.fileList();

            //删除重叠的元素，获取多余的图片列表
            imgQiNiu.removeAll(imgDb);

            if(imgQiNiu.size() > 0){
                //List转String数组
                String[] keys = imgQiNiu.toArray(new String[]{});
                //批量删除七牛云上冗余的图片
                QiNiuUtil.deleteFile(keys);
            }

            LOGGER.info("【定时任务-清除七牛云多余图片】运行结束>>>>>>success");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("【定时任务-清除七牛云多余图片】运行异常>>>>>>exception", e);
        }
    }
}
